<template>
  <div class="add-role-container">
    <div class="page-header">
      <h1 style="color: white;">添加新角色</h1>
      <el-button @click="navigateBack" icon="ArrowLeft">返回角色列表</el-button>
    </div>

    <el-card class="role-form-card">
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="formRules"
        status-icon
        label-width="120px"
        class="role-form"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="roleForm.name"
            placeholder="请输入角色名称"
            maxlength="50"
            show-word-limit
          />
          <!-- <div class="form-hint">角色名称只能包含字母、数字和下划线，长度2-50个字符</div> -->
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            placeholder="请输入角色描述"
            type="textarea"
            :rows="4"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="权限分配" prop="permissions">
          <div class="permission-section">
            <el-checkbox-group v-model="roleForm.permissions">
              <div class="permission-groups">
                <div class="permission-group" v-for="group in permissionGroups" :key="group.id">
                  <div class="permission-group-header">{{ group.label }}</div>
                  <div class="permission-options">
                    <el-checkbox
                      v-for="perm in group.permissions"
                      :key="perm.value"
                      :value="perm.value"
                    >
                      {{ perm.label }}
                    </el-checkbox>
                  </div>
                </div>
              </div>
            </el-checkbox-group>
          </div>
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { rolenameRules,permissionRules,descriptionRules } from '../utils/validationRules';

const router = useRouter();
const roleFormRef = ref(null);
const submitting = ref(false);

// 角色表单数据
const roleForm = ref({
  name: '',
  description: '',
  permissions: []
});

// 权限组数据
const permissionGroups = ref([
  {
    id: 'user',
    label: '用户管理',
    permissions: [
      { value: 'user:read', label: '查看用户' },
      { value: 'user:create', label: '创建用户' },
      { value: 'user:update', label: '编辑用户' },
      { value: 'user:delete', label: '删除用户' }
    ]
  },
  {
    id: 'role',
    label: '角色管理',
    permissions: [
      { value: 'role:read', label: '查看角色' },
      { value: 'role:create', label: '创建角色' },
      { value: 'role:update', label: '编辑角色' },
      { value: 'role:delete', label: '删除角色' }
    ]
  },
  {
    id: 'system',
    label: '系统设置',
    permissions: [
      { value: 'dashboard:view', label: '查看仪表盘' },
      { value: 'setting:read', label: '查看设置' },
      { value: 'setting:update', label: '更新设置' },
      { value: 'log:view', label: '查看日志' }
    ]
  }
]);
async function checkRoleNameUnique(rule, value, callback) {
  if (!value) {
    callback();
    return;
  }

  try {
    // 模拟API调用检查角色名称唯一性
    const response = await fetch('/api/check-role-name', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: value })
    });
    const result = await response.json();

    if (result.exists) {
      callback(new Error('角色名称已存在，请使用其他名称'));
    } else {
      callback();
    }
  } catch (error) {
    callback(new Error('检查名称失败，请稍后重试'));
  }
}
// 表单验证规则
const formRules = {
  name: [
    rolenameRules,
    { validator: checkRoleNameUnique, trigger: 'blur' }
  ],
  description: descriptionRules,
  permissions: permissionRules
};

// 检查角色名称唯一性


// 提交表单
async function handleSubmit() {
  try {
    await roleFormRef.value.validate();
    submitting.value = true;

    // 模拟API提交
    const response = await fetch('/api/roles', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(roleForm.value)
    });

    if (response.ok) {
      ElMessage.success('角色创建成功');
      router.push('/role-management');
    } else {
      const error = await response.json();
      ElMessage.error(error.message || '角色创建失败');
    }
  } catch (error) {
    console.log(roleForm.value);
    
    console.error('提交失败:', error);
    ElMessage.error('表单验证失败，请检查输入内容');
  } finally {
    submitting.value = false;
  }
}

// 重置表单
function resetForm() {
  console.log(roleForm.value);  
  roleFormRef.value.resetFields();
  
  
  // 显式重置权限选择数组
  roleForm.value.permissions = [];
}

// 返回角色列表
function navigateBack() {
  router.push('/roles/list');
}

onMounted(() => {
  // 页面加载时的初始化逻辑
});
</script>

<style scoped>
.add-role-container {
  padding: 20px;
background: linear-gradient(135deg, #6a9fff 0%, #2a5298 100%);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row-reverse;
  margin-bottom: 20px;
}

.role-form-card {
  max-width: 800px;
  margin: 0 auto;
}

.role-form {
  padding: 20px 0;
}

.form-hint {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.permission-section {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
}

.permission-groups {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.permission-group-header {
  font-weight: 500;
  margin-bottom: 10px;
  color: #303133;
}

.permission-options {
  display: flex;
  flex-wrap: wrap;
  gap: 15px 25px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 30px;
}
</style>